
var md5 =require('md5')

//config配置
class util{

	constructor(){

	}

	// 验证参数
	checkSigin(data,socket){
		if(!data.getSign || !data.getSign.time || !data.getSign.random || !data.getSign.paySign){
			socket.emit('progress number', this.returnBeiZhu('缺少签名必要验证参数！'));
			return false;	
		};
		let sigin=this.signwx({
			name:'wangwei',
			company:'morning-star',
			time:data.getSign.time,
			random:data.getSign.random
		});
		if(sigin.paySign === data.getSign.paySign){
			socket.emit('progress number', this.returnBeiZhu('签名成功 OK！'));
			return true;	
		}else{
			socket.emit('progress number', this.returnBeiZhu('签名不一致！'));
			return false;	
		}
	}

	/*本地加密算法*/
	signwx(json){
		var wxkey='ZANEWANGWEI123456AGETEAMABmiliH'; 
		/*对json的key值排序 */
		var arr=[];
		var sortJson={};
		var newJson=json;
		for(var key in json){
			if(json[key]){
				arr.push(key);
			}
		}
		arr.sort(function(a,b){
			return a.localeCompare(b);
		});
		for(var i=0,len=arr.length;i<len;i++){
			sortJson[arr[i]]=json[arr[i]]
		}
		/*拼接json为key=val形式*/
		var str="";
		for(var key in sortJson){
			str+=key+"="+sortJson[key]+'&';
		}
		str+='key='+wxkey;
		/*md5*/
		var md5Str=md5(str);
		var signstr = md5Str.toUpperCase();
		/*获得有sign参数的json*/
		newJson['paySign']=signstr;
		return newJson;
	}

	//返回备注
	returnBeiZhu(str){
		return `
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------${str}---------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
		`
	}

	// 检查接口来源权限
	checkReferer(referer){
		let begin = false;
		if(referer=='http://127.0.0.1:8000/' || referer=='http://zane.morning-star.cn/'){
			begin = true;
		}
		return begin;
	}



}


module.exports = new util();



